package com.fwtai.tool;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

public final class ToolClient{

  public static void responseJson(final String json,final HttpServletResponse response){
    response.setContentType("text/html;charset=utf-8");
    response.setHeader("Cache-Control","no-cache");
    try(final PrintWriter writer = response.getWriter()){
      writer.write(json);
      writer.flush();
    }catch(final IOException ignored){}
  }

  public static String createJson(final int code,final String msg,final Object data){
    final ObjectMapper objectMapper = new ObjectMapper();
    try {
      if(data == null){
        return "{\"code\":"+code+",\"msg\":\"<title>系统提示</title>"+msg+"\"}";
      }else{
        final String value = objectMapper.writeValueAsString(data);
        return "{\"code\":"+code+",\"msg\":\"<title>系统提示</title>"+msg+"\",\"data\":"+value+"}";
      }
    } catch (final Exception ignored){
      return "{\"code\":205,\"msg\":\"<title>系统提示</title>服务出现错误\"}";
    }
  }

  public static String listToJsonArray(final List<String> list){
    final StringBuilder all = new StringBuilder("[");
    final StringBuilder json = new StringBuilder();
    for(int i = list.size() - 1; i >= 0; i--){
      final String value = list.get(i);
      if(json.length() > 0){
        json.append(",{\"path\",").append("\"").append(value).append("\"}");
      }else{
        json.append("{\"path\":").append("\"").append(value).append("\"}");
      }
    }
    all.append(json).append("]");
    return all.toString();
  }
}